package cn.songdragon.zboschina;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClient {

	private static HttpClient client;

	public static HttpClient getInstance() {
		if (client == null) {
			client = new HttpClient();
		}
		return client;
	}

	CloseableHttpClient httpClient;

	String userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36";

	public HttpClient() {
		httpClient = HttpClients.custom().setMaxConnTotal(4).build();
	}

	public String get(String url) {
		HttpClientContext context = HttpClientContext.create();
		return get(url, context, null);

	}

	public String get(String url, HttpClientContext context, Map<String, String> header) {
		HttpResponse response = getHttpResponse(url, context, header);
		String body = response.getBody();
		if (body == null) {
			body = "";
		}
		return body;

	}

	public HttpResponse getHttpResponse(String url, HttpClientContext context, Map<String, String> reqHeaders) {
		// CloseableHttpResponse response = getResponse(url, context);
		HttpGet get = new HttpGet(url);
		HttpResponse httpResponse = new HttpResponse();
		try {

			if (reqHeaders != null && reqHeaders.size() > 0) {
				Set<Entry<String, String>> headerSet = reqHeaders.entrySet();
				for (Entry<String, String> headerEntry : headerSet) {
					String key = headerEntry.getKey();
					String value = headerEntry.getValue();
					get.setHeader(key, value);
				}
				if (!reqHeaders.containsKey(HttpHeaders.USER_AGENT)) {
					get.setHeader(HttpHeaders.USER_AGENT, this.userAgent);
				}
			} else {
				get.setHeader(HttpHeaders.USER_AGENT, this.userAgent);
			}
			CloseableHttpResponse response = this.httpClient.execute(get, context);
			if (response != null) {
				String responseBody = EntityUtils.toString(response.getEntity());
				int statusCode = response.getStatusLine().getStatusCode();
				Header[] headers = response.getAllHeaders();
				String contentType = response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();
				httpResponse.setBody(responseBody);
				httpResponse.setStatus(statusCode);
				httpResponse.setHeaders(headers);
				httpResponse.setContentType(contentType);

			}
		} catch (ClientProtocolException e) {
			// e.printStackTrace();
		} catch (IOException e) {
			// e.printStackTrace();
		} finally {
			get.reset();
		}
		return httpResponse;
	}

}
